package com.shisfish.util;

import com.zhijiaoyun.common.DateUtils;
import com.zhijiaoyun.enumeration.SexEnum;
import com.zhijiaoyun.model.User;
import org.apache.poi.xssf.usermodel.*;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * @author shisfish
 * @date 2017/6/6
 */
public class ExcelUtil<T> {

    public XSSFWorkbook getWorkBook(List<String> headers, String sheetName) {
        // 声明一个工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 生成一个表格
        XSSFSheet sheet = workbook.createSheet(sheetName);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 20);
        // 产生表格标题行
        XSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.size(); i++) {
            XSSFCell cell = row.createCell(i);
            XSSFRichTextString text = new XSSFRichTextString(headers.get(i));
            cell.setCellValue(text);
        }

        return workbook;
    }

    public XSSFWorkbook getWorkBookUser(List<String> headers, List<String> properties, Collection<T> dataset, String sheetName) {
        XSSFWorkbook workbook = getWorkBook(headers, sheetName);

        // 生成一个表格
        XSSFSheet sheet = workbook.getSheetAt(0);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 20);
        // 产生表格标题行
        XSSFRow row = null;
        try {
            // 遍历集合数据，产生数据行
            Iterator<T> it = dataset.iterator();
            int index = 0;
            while (it.hasNext()) {
                index++;
                row = sheet.createRow(index);
                T t = it.next();
                // 利用反射，根据javabean属性的先后顺序，动态调用getXxx()方法得到属性值
                for (int i = 0, length = properties.size(); i < length; i++) {
                    String property = properties.get(i);
                    XSSFCell cell = row.createCell(i);
                    Field field = t.getClass().getDeclaredField(property);
                    String fieldName = field.getName();
                    String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                    Class<? extends Object> tCls = t.getClass();
                    Method getMethod = tCls.getMethod(getMethodName, new Class[]{});
                    Object value = getMethod.invoke(t, new Object[]{});
                    // 判断值的类型后进行强制类型转换
                    String textValue = null;
                    // 其它数据类型都当作字符串简单处理
                    if (value != null && value != "") {
                        textValue = value.toString();
                    }
                    if ("sex".equals(property)) {
                        if (SexEnum.MALE.getIndexStr().equals(textValue)) {
                            textValue = SexEnum.MALE.getDescript();
                        } else if (SexEnum.FEMALE.getIndexStr().equals(textValue)) {
                            textValue = SexEnum.FEMALE.getDescript();
                        } else {
                            textValue = SexEnum.UNKNOW.getDescript();
                        }
                    } else if ("createTime".equals(property)){
                        textValue = DateUtils.getDateFormat(DateUtils.getDateFormat(textValue, "EEE MMM dd HH:mm:ss z yyyy"), "yyyy-MM-dd");
                    }
                    if (textValue != null) {
                        XSSFRichTextString richString = new XSSFRichTextString(textValue);
                        cell.setCellValue(richString);
                    }
                }
            }
            return workbook;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public void exportExcel(List<String> headers, List<String> properties, Collection<T> dataset, String fileName) {
        // 声明一个工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 生成一个表格
        XSSFSheet sheet = workbook.createSheet(fileName);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 20);
        // 产生表格标题行
        XSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.size(); i++) {
            XSSFCell cell = row.createCell(i);
            XSSFRichTextString text = new XSSFRichTextString(headers.get(i));
            cell.setCellValue(text);
        }
        try {
            // 遍历集合数据，产生数据行
            Iterator<T> it = dataset.iterator();
            int index = 0;
            while (it.hasNext()) {
                index++;
                row = sheet.createRow(index);
                T t = it.next();
                // 利用反射，根据javabean属性的先后顺序，动态调用getXxx()方法得到属性值
                for (int i = 0, length = properties.size(); i < length; i++) {
                    String property = properties.get(i);
                    XSSFCell cell = row.createCell(i);
                    Field field = t.getClass().getDeclaredField(property);
                    String fieldName = field.getName();
                    String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                    Class<? extends Object> tCls = t.getClass();
                    Method getMethod = tCls.getMethod(getMethodName, new Class[]{});
                    Object value = getMethod.invoke(t, new Object[]{});
                    // 判断值的类型后进行强制类型转换
                    String textValue = null;
                    // 其它数据类型都当作字符串简单处理
                    if (value != null && value != "") {
                        textValue = value.toString();
                    }
                    if (textValue != null) {
                        XSSFRichTextString richString = new XSSFRichTextString(textValue);
                        cell.setCellValue(richString);
                    }
                }
            }
            getExportedFile(workbook, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getExportedFile(XSSFWorkbook workbook, String filePath) {
        BufferedOutputStream fos = null;
        try {
            File file = new File(filePath);
            fos = new BufferedOutputStream(new FileOutputStream(file));
            workbook.write(fos);
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
		return filePath;
    }

}
